package com.yanyeori.framework.security.service;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * 用户注册、登录页面通信用户名、密码解密
 *
 * @author chenkuan 2022/8/5
 */
public class UsernamePasswordDecrypt {

    private static volatile UsernamePasswordDecrypt decrypt;

    /**
     * 重写用户名解密
     *
     * @param request  HttpServletRequest
     * @param username 用户名
     * @return 解密后的用户名
     */
    public String username(HttpServletRequest request, String username) throws Exception {
        return username;
    }

    /**
     * 重写密码解密
     *
     * @param request  HttpServletRequest
     * @param password 密码
     * @return 解密后的密码
     */
    public String password(HttpServletRequest request, String password) throws Exception {
        return password;
    }

    public static UsernamePasswordDecrypt get() {
        if (decrypt == null) {
            synchronized (UsernamePasswordDecrypt.class) {
                if (decrypt == null) {
                    ServiceLoader<UsernamePasswordDecrypt> serviceLoader = ServiceLoader.load(UsernamePasswordDecrypt.class);
                    Iterator<UsernamePasswordDecrypt> iterator = serviceLoader.iterator();
                    if (iterator.hasNext()) {
                        decrypt = iterator.next();
                    } else {
                        decrypt = new UsernamePasswordDecrypt();
                    }
                }
            }
        }
        return decrypt;
    }
}
